package com.school.gmz.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.gmz.common.Result;
import com.school.gmz.entity.Borrow;
import com.school.gmz.mapper.BorrowMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/borrow")
@Api(tags = "借阅管理") // 定义API的分类
public class BorrowController {
    @Resource
    BorrowMapper borrowMapper;

    // 添加借阅记录
    @PostMapping
    @ApiOperation(value = "添加借阅记录", notes = "创建一个新的借阅记录")
    public Result<?> save(@RequestBody Borrow borrow){
        borrowMapper.insert(borrow);
        return Result.success();
    }

    // 更新借阅记录
    @PutMapping
    @ApiOperation(value = "更新借阅记录", notes = "根据ID更新借阅记录")
    public Result<?> update(@RequestBody Borrow borrow){
        borrowMapper.updateById(borrow);
        return Result.success();
    }

    // 删除借阅记录
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除借阅记录", notes = "根据ID删除借阅记录")
    public Result<?> delete(@ApiParam(value = "借阅记录ID", required = true) @PathVariable Long id){
        borrowMapper.deleteById(id);
        return Result.success();
    }

    // 查询借阅记录
    @GetMapping
    @ApiOperation(value = "查询借阅记录", notes = "支持分页和关键字搜索")
    public Result<?> findPage(@ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
                              @ApiParam(value = "每页记录数", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize,
                              @ApiParam(value = "搜索关键字", defaultValue = "") @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Borrow> wrapper = Wrappers.<Borrow>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(Borrow::getName, search);
        }
        Page<Borrow> BorrowPage = borrowMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(BorrowPage);
    }
}